package com.share.finance.risk.third.web;

import com.alibaba.fastjson.JSON;
import com.share.common.common.Result;
import com.share.common.utils.IpUtil;
import com.share.finance.risk.common.model.sys.LocalRequest;
import com.share.finance.risk.common.model.sys.ThirdRequest;
import com.share.finance.risk.third.service.AsyncDealService;
import com.share.finance.risk.third.service.IChannelRequestLogService;
import com.share.finance.risk.third.service.IThirdRequestLogService;
import com.share.finance.risk.third.service.MainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
public class MainController {
    @Autowired
    private MainService mainService;
    @Autowired
    private AsyncDealService asyncDealService;
    @Autowired
    private IThirdRequestLogService thirdRequestLogService;
    @Autowired
    private IChannelRequestLogService channelRequestLogService;

    /**
     * 三方接口
     *
     * @param requestData
     * @return
     */
    @PostMapping(value = "/info")
    public Result info(@RequestBody ThirdRequest requestData, HttpServletRequest request) {
        Map<String, Object> res = null;
        String strParam = JSON.toJSONString(requestData);
        String sessionId = requestData.getSessionId();
        long startTime = System.currentTimeMillis();
        log.info("info-sessionId={},requestData = {}", sessionId, strParam);
        try {
            res = mainService.info(requestData);
        } catch (Exception e) {
            log.error("接口调用异常param={}", strParam, e);
        } finally {
            long endTime = System.currentTimeMillis();
            asyncDealService.thirdRequestLogServiceSaveLog(requestData, res, endTime - startTime, IpUtil.getIpAddress(request));
        }
        return Result.success(res);
    }

    /**
     * 本地变量
     *
     * @param requestData
     * @return
     */
    @PostMapping(value = "/local")
    public Result local(@RequestBody LocalRequest requestData, HttpServletRequest request) {
        Map<String, Object> res = null;
        String strParam = JSON.toJSONString(requestData);
        String sessionId = requestData.getSessionId();
        long startTime = System.currentTimeMillis();
        log.info("local-sessionId={},requestData = {}", sessionId, strParam);
        try {
            res = mainService.local(requestData);
        } catch (Exception e) {
            log.error("本地变量调用异常param={}", strParam, e);
        } finally {
            long endTime = System.currentTimeMillis();
            asyncDealService.localRequestLogServiceSaveLog(requestData, res, endTime - startTime, IpUtil.getIpAddress(request));
        }
        return Result.success(res);
    }
}
